package impl.parser;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Set;

import impl.core.UDecideManager;
import impl.util.UtilityAssertion;
import interfaces.UDecideParserInterface;

import org.coode.owlapi.manchesterowlsyntax.ManchesterOWLSyntaxEditorParser;
import org.semanticweb.owlapi.expression.OWLEntityChecker;
import org.semanticweb.owlapi.expression.ShortFormEntityChecker;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.util.BidirectionalShortFormProviderAdapter;
import org.semanticweb.owlapi.util.ShortFormProvider;
import org.semanticweb.owlapi.util.SimpleShortFormProvider;

public class UDecideParser implements UDecideParserInterface {

	private ManchesterOWLSyntaxEditorParser	parser;

	@Override
	public OWLClassExpression parseOWLClassExpression(String s) {
		prepareParser(s);
		OWLClassExpression expr;
		try {
			expr = this.parser.parseClassExpression();
			return expr;
		} catch (Exception ex) {
			System.out.println(ex);
			return null;
		}
	}

	private void prepareParser(String input) {
		OWLOntology kb = UDecideManager.getInstance().getKnowledgeBase();

		this.parser = new ManchesterOWLSyntaxEditorParser(UDecideManager.getInstance().getOWLlDataFactory(), input);
		this.parser.setDefaultOntology(kb);

		Set<OWLOntology> importsClosure = kb.getImportsClosure();
		ShortFormProvider shortFormProvider = new SimpleShortFormProvider();
		BidirectionalShortFormProviderAdapter bidiShortFormProvider = new BidirectionalShortFormProviderAdapter(importsClosure, shortFormProvider);
		OWLEntityChecker entityChecker = new ShortFormEntityChecker(bidiShortFormProvider);
		this.parser.setOWLEntityChecker(entityChecker);
	}

	@Override
	public UtilityAssertion parseUtilityAssertion(String clEx, String uValue) {
		try {
			return new UtilityAssertion(clEx, NumberFormat.getInstance().parse(uValue).doubleValue(), parseOWLClassExpression(clEx));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
